package com.flowershop.service;

import com.flowershop.dao.OrderDao;
import com.flowershop.dao.CartDao;
import com.flowershop.model.Order;
import com.flowershop.model.OrderItem;
import com.flowershop.model.CartItem;
import java.util.List;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.SQLException;
import com.flowershop.util.DBUtil;

public class OrderService {
    private OrderDao orderDao = new OrderDao();
    private CartDao cartDao = new CartDao();
    
    public Order createOrderFromCart(Integer userId) {
        // 获取购物车内容
        List<CartItem> cartItems = cartDao.getCartItems(userId);
        if (cartItems.isEmpty()) {
            return null;
        }
        
        // 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setStatus("pending");
        
        // 计算总金额并转换购物车项为订单项
        List<OrderItem> orderItems = new ArrayList<>();
        java.math.BigDecimal totalAmount = java.math.BigDecimal.ZERO;
        
        for (CartItem cartItem : cartItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setFlowerId(cartItem.getFlowerId());
            orderItem.setQuantity(cartItem.getQuantity());
            orderItem.setPrice(cartItem.getPrice());
            orderItems.add(orderItem);
            
            totalAmount = totalAmount.add(cartItem.getSubtotal());
        }
        
        order.setTotalAmount(totalAmount);
        order.setItems(orderItems);
        
        // 保存订单
        Order createdOrder = orderDao.createOrder(order);
        if (createdOrder != null) {
            // 清空购物车
            clearCart(userId);
        }
        
        return createdOrder;
    }
    
    private void clearCart(Integer userId) {
        // 获取购物车项并逐个删除
        List<CartItem> cartItems = cartDao.getCartItems(userId);
        for (CartItem item : cartItems) {
            cartDao.removeFromCart(item.getId());
        }
    }
    
    public List<Order> getOrdersByUserId(Integer userId) {
        return orderDao.getOrdersByUserId(userId);
    }
    
    public boolean updateOrderStatus(Integer orderId, String status) {
        return orderDao.updateOrderStatus(orderId, status);
    }
    
    public List<Order> getAllOrders() {
        return orderDao.getAllOrders();
    }
    
    public static final class OrderStatus {
        public static final String PENDING = "pending";
        public static final String PAID = "paid";
        public static final String SHIPPED = "shipped";
        public static final String COMPLETED = "completed";
        public static final String CANCELLED = "cancelled";
    }
} 